<route lang="yaml">
meta:
enabled: false
</route>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import baiduApi from '@/api/modules/baiduTransApi'
import apiUser from '@/api/modules/userMange'
import useSettingsStore from '@/store/modules/settings'
import { ElMessage, ElMessageBox } from 'element-plus'

defineOptions({
  name: 'RanksDeatil',
})
const route = useRoute()
const router = useRouter()
const tabbar = useTabbar()
const settingsStore = useSettingsStore()
const loading = ref(false)
const updateImg = ref(false)
const formRef = useTemplateRef<FormInstance>('formRef')
const userRoles = ref<any[]>([]) // 登录用户角色
const isSuperAdmin = ref(false) // 是否为超级管理员

// 学校类
interface SchoolOption {
  label: string
  value: number
}

// 角色类
interface RoleOption {
  label: string
  value: number
}

const schoolOptions = ref<SchoolOption[]>([]) // 加载学校列表
const RoleOptions = ref<RoleOption[]>([]) // 加载角色列表
const RanksOptions = ref([
  { label: '无', value: 0 },
  { label: '校园大使', value: 1 },
])
const form = ref({
  userId: route.params.id as string | number ?? '',
  nickName: '',
  phonenumber: '',
  avatar: '',
  sex: '',
  status: '',
  password: '',
  schoolId: -1, // 学校id
  schoolName: '', // 学校
  ranks: '', // 头衔
  briefIntroduction: '', // 简介
  briefIntroductionEn: '', // 英文简介
  designer: '', // 描述
  imagePhoto: '',
  roles: [] as number[],
})
const formRules = ref<FormRules>({
  nickName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { pattern: /^[\u4E00-\u9FA5a-z0-9]{1,20}$/i, message: '昵称只能包含中英文和数字，且不超过20个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'blur' },
  ],
  phonenumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'blur' },
  ],
  avatar: [
    { required: true, message: '请上传头像', trigger: 'blur' },
  ],
  schoolId: [ // 新增
    { required: true, message: '请输入学校ID', trigger: 'blur' },
  ],
  // ranks: [ // 新增
  //   { required: true, message: '请输入头衔', trigger: 'blur' },
  // ],
  roles: [ // 新增
    { required: true, message: '请输入角色', trigger: 'blur' },
  ],
  briefIntroduction: [
    { pattern: /^[\u4E00-\u9FA5a-z0-9]{1,200}$/i, message: '简介只能包含中文、英文和数字，且不超过200个字符', trigger: 'blur' },
  ],
  briefIntroductionEn: [
    { pattern: /[#%&?]/, message: '英文简介只能包含英文字母、数字和空格，且不超过200个字符', trigger: 'blur' },
  ],
  designer: [ // 新增
    { required: true, message: '请输入设计师', trigger: 'blur' },
  ],
  imagePhoto: [ // 新增
    { required: true, message: '请上传图片', trigger: 'blur' },
  ],
})

onMounted(async () => {
  loading.value = true
  try {
    await Promise.all([
      loadSchoolOptions(),
      loadRoleOptions(),
      getUserInfo(),
    ])
    if (form.value.userId !== '') {
      getInfo()
    }
  }
  catch (error) {
    console.error('加载失败', error)
    ElMessage.error('数据加载失败')
  }
  finally {
    loading.value = false
  }
})
function getInfo() {
  loading.value = true
  console.log('loading.value=', loading.value)
  apiUser.detail(form.value.userId).then((res: any) => {
    loading.value = false
    form.value.nickName = res.data.nickName
    form.value.phonenumber = res.data.phonenumber
    form.value.avatar = res.data.avatar
    form.value.sex = res.data.sex
    form.value.status = res.data.status
    form.value.schoolId = Number(res.data.schoolId)
    form.value.schoolName = res.data.schoolName
    form.value.ranks = res.data.ranks
    form.value.briefIntroduction = res.data.briefIntroduction
    form.value.briefIntroductionEn = res.data.briefIntroductionEn
    form.value.designer = res.data.designer
    form.value.imagePhoto = res.data.imagePhoto
    form.value.roles = res.data.roles.map((role: any) => role.roleId)
  })
}

const translateText = async (text: string, from: string, to: string): Promise<string> => {
  try {
    const response = await baiduApi.translate({
      query: text,
      from,
      to,
    })
    const data = response.data
    return data.trans_result[0].dst
  }
  catch (error) {
    console.error('Translation failed:', error)
    ElMessage.error('翻译失败，请稍后再试')
    return ''
  }
}
const translateToEnglish = async (text: string): Promise<string> => {
  return translateText(text, 'zh', 'en')
}
const translateBriefIntroductionToEnglish = async () => {
  if (form.value.briefIntroduction && form.value.briefIntroduction.trim() !== '') {
    form.value.briefIntroductionEn = await translateToEnglish(form.value.briefIntroduction)
  }
}

function onSubmit() {
  return new Promise<void>(() => {
    formRef.value?.validate((valid) => {
      if (valid) {
        if (form.value.userId === '') {
          apiUser.create(form.value).then(() => {
            ElMessage.success({
              message: '新增成功',
            })
            goBack()
          })
        }
        else {
          form.value.userId = Number(form.value.userId)
          apiUser.edit(form.value).then(() => {
            console.log('form.value=', form.value)
            ElMessage.success({
              message: '编辑成功',
            })
            goBack()
          })
        }
      }
    })
  })
}

async function handleSuccess(file: any) {
  if (form.value.userId !== '') {
    await ElMessageBox.alert('不允许修改', '提示', {
      confirmButtonText: '确定',
    })
    return false
  }
  updateImg.value = true
  const formData = new FormData()
  formData.append('file', file.file)
  return await apiUser.uploadAvatar(formData).then((res: any) => {
    updateImg.value = false
    if (res.code === 200) {
      form.value.avatar = res.data
      ElMessage.success({
        message: '上传成功',
      })
    }
  })
}
async function handleSuccessimagePhoto(file: any) {
  updateImg.value = true
  const formData = new FormData()
  formData.append('file', file.file)
  return await apiUser.uploadAvatar(formData).then((res: any) => {
    updateImg.value = false
    if (res.code === 200) {
      form.value.imagePhoto = res.data
      ElMessage.success({
        message: '上传成功',
      })
    }
  })
}
// 获取学校列表
async function loadSchoolOptions() {
  try {
    const res = await apiUser.getSchoolList()
    schoolOptions.value = res.data.map((item: any) => ({
      label: item.schoolName,
      value: item.schoolId,
    }))
  }
  catch (error) {
    console.error('加载失败', error)
  }
}

async function getUserInfo() {
  try {
    const res = await apiUser.getUserInfo()
    userRoles.value = res.data.roles
    isSuperAdmin.value = res.data.roles.some((role: any) => role.roleId === 1)
  }
  catch (error) {
    console.error('加载失败', error)
  }
}
// 获取用户列表
async function loadRoleOptions() {
  try {
    const res = await apiUser.getRoleList()

    RoleOptions.value = res.data.map((item: any) => ({
      label: item.roleName,
      value: item.roleId,
    }))
  }
  catch (error) {
    console.error('加载失败', error)
  }
}

function onCancel() {
  goBack()
}

const schoolIdProxy = computed({
  get: () => (form.value.schoolId === -1 ? '' : form.value.schoolId),
  set: (val) => {
    form.value.schoolId = val === '' ? -1 : Number(val)
  },
})

// 返回列表页
function goBack() {
  if (settingsStore.settings.tabbar.enable && settingsStore.settings.tabbar.mergeTabsBy !== 'activeMenu') {
    tabbar.close({ name: 'userManagement' })
  }
  else {
    router.push({ name: 'userManagement' })
  }
}
</script>

<template>
  <div class="absolute size-full flex flex-col">
    <FaPageHeader :title="route.name === 'userManagementCreate' ? '新增用户' : '编辑信息'" class="mb-0">
      <ElButton size="default" round @click="goBack">
        <template #icon>
          <FaIcon name="i-ep:arrow-left" />
        </template>
        返回
      </ElButton>
    </FaPageHeader>
    <ElForm
      ref="formRef"
      v-loading="loading"
      :model="form"
      :rules="formRules"
      label-width="120px"
      label-suffix="："
      element-loading-text="数据加载中..."
      element-loading-background="rgba(255, 255, 255, 0.8)"
    >
      <FaLayoutContainer
        right-side-width="500px" hide-right-side-toggle class="static"
        right-side-class="flex flex-col"
      >
        <ElFormItem label="用户名称" prop="nickName">
          <ElInput
            v-model="form.nickName"
            placeholder="请输入用户名称"
            :disabled="form.userId !== ''"
            @input="(value) => form.nickName = value.replace(/[^\\u4e00-\u9fa5a-zA-Z0-9]/g, '')"
          />
        </ElFormItem>

        <ElFormItem label="手机号码" prop="phonenumber">
          <ElInput v-model="form.phonenumber" :disabled="form.userId !== ''" placeholder="请输入手机号" />
        </ElFormItem>
        <ElFormItem label="帐号状态" prop="status">
          <ElSwitch
            v-model="form.status" inline-prompt active-text="启用" inactive-text="停用" active-value="0"
            :disabled="form.userId !== ''"
            inactive-value="1"
          />
        </ElFormItem>
        <ElFormItem label="上传头像" prop="avatar">
          <!-- 新增模式使用上传组件 -->
          <ImageUpload
            v-if="form.userId === ''"
            v-model="form.avatar"
            :loading="updateImg"
            action=""
            name="image"
            :width="150"
            :height="150"
            :http-request="handleSuccess"
          />
          <!-- 编辑模式使用预览组件 -->
          <div v-else class="image-preview-container">
            <ImagePreview
              v-if="form.avatar"
              :src="form.avatar"
              class="preview-item"
              alt="用户头像"
              :width="150"
              :height="150"
            />
          </div>
        </ElFormItem>

        <!--        <ElFormItem label="用户性别" prop="sex"> -->
        <!--          <ElRadioGroup v-model="form.sex" :disabled="form.userId !== ''"> -->
        <!--            <ElRadioButton value="2"> -->
        <!--              保密 -->
        <!--            </ElRadioButton> -->
        <!--            <ElRadioButton value="0"> -->
        <!--              男 -->
        <!--            </ElRadioButton> -->
        <!--            <ElRadioButton value="1"> -->
        <!--              女 -->
        <!--            </ElRadioButton> -->
        <!--          </ElRadioGroup> -->
        <!--        </ElFormItem> -->
        <ElFormItem v-if="form.userId === ''" label="设置密码" prop="password">
          <ElInput v-model="form.password" type="password" placeholder="请输入密码" />
        </ElFormItem>
        <ElFormItem label="所属学校" prop="schoolId">
          <el-select
            v-model="schoolIdProxy"
            filterable
            :disabled="form.userId !== ''"
            placeholder="请选择学校"
          >
            <el-option
              v-for="item in schoolOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </ElFormItem>
        <ElFormItem v-auth="'system:role:add'" label="角色" prop="roles">
          <ElCheckboxGroup v-model="form.roles" :disabled="form.userId !== '' && !isSuperAdmin">
            <ElCheckbox
              v-for="item in RoleOptions"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </ElCheckbox>
          </ElCheckboxGroup>
        </ElFormItem>
        <ElFormItem label="简介" prop="briefIntroduction">
          <ElInput v-model="form.briefIntroduction" :disabled="form.userId !== ''" placeholder="请输入简介">
            <template #append>
              <ElButton :disabled="form.userId !== ''" @click="translateBriefIntroductionToEnglish">
                翻译
              </ElButton>
            </template>
          </ElInput>
        </ElFormItem>
        <ElFormItem label="英文简介" prop="briefIntroductionEn">
          <ElInput v-model="form.briefIntroductionEn" :disabled="form.userId !== ''" placeholder="请输入英文简介" />
        </ElFormItem>
        <ElFormItem v-if="form.userId !== ''" label="头衔" prop="ranks">
          <el-select v-model="form.ranks" :disabled="form.userId !== ''" placeholder="请选择头衔">
            <el-option
              v-for="item in RanksOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </ElFormItem>

        <ElFormItem label="形象照" prop="imagePhoto">
          <!-- 新增模式使用上传组件 -->
          <ImageUpload
            v-if="form.userId === ''"
            v-model="form.imagePhoto"
            :loading="updateImg"
            action=""
            name="imagePhoto"
            :width="150"
            :height="150"
            :http-request="handleSuccessimagePhoto"
          />

          <!-- 编辑模式使用预览组件 -->
          <div v-else class="image-preview-container">
            <ImagePreview
              :src="form.imagePhoto"
              class="preview-image"
              alt="形象照"
              :width="150"
              :height="150"
            />
          </div>
        </ElFormItem>

        <FaFixedActionBar>
          <ElButton type="primary" size="large" @click="onSubmit">
            提交
          </ElButton>
          <ElButton size="large" @click="onCancel">
            取消
          </ElButton>
        </FaFixedActionBar>
      </FaLayoutContainer>
    </ElForm>
  </div>
</template>

<style scoped>
.el-form {
  display: flex;
  flex: 1;
  overflow: auto;
}

.label-tip {
  display: inline-flex;
  margin-left: 10px;
  color: var(--el-text-color-disabled);
}
</style>
